import axios from 'axios';
import Tools from '@untils/tools.jsx';

const loading = document.querySelector('#page-loading');
const service = axios.create();
const isMock = false;
// 全局请求拦截
service.interceptors.request.use((config) => {
    let url = encodeURI(config.url);
    url.indexOf('?') > -1 ? url += `&_t=${new Date().getTime()}` : url += `?_t=${new Date().getTime()}`;
    config.url = url;
    return config;
});

// 添加响应拦截器
service.interceptors.response.use((response) => {
    loading.style.display = 'none';
    return response;
}, (error) => {
    loading.style.display = 'none';
    return Promise.reject(error);
});

export default class request {
    // 正常数据请求
    axios(options) {
        // 空转为null
        options = Tools.transData(options);
        return new Promise((resolve, reject) => {
            let baseUrl = isMock
                ? 'https://www.easy-mock.com/mock/5b95bea7dd236325f85bfa30/prevdata'
                : '';
            void(options.loading === false ? 0 : loading.style.display = 'block');
            service({
                baseURL: baseUrl,
                method: options.method || 'get',
                url: options.url || '',
                params: options.params || null,
                data: options.data || null,
                timeout: options.timeout || null,
            }).then(res => {
                let resData = res.data;
                if (resData.code === '000000') {
                    resolve(resData.content);
                } else if (resData.code === 104) {

                } else {
                    reject(resData);
                }
            }, err => {
                // 请求错误
                reject(err.response||err);
            }).catch(err => {
                // then 错误
                loading.style.display = 'none';
                reject(err.response||err);
            });
        })
    }

    ajaxList(options, _this = null) {
        return new Promise((resolve, reject) => {
            let {paging = true} = options;
            this.axios(options).then(data => {
                let list = data.content || [];
                //分页
                let pagination =
                    list.length && paging ? {
                        current: data.currentPage,
                        pageSize: data.pageSize,
                        total: data.totalCount,
                        showTotal: () => {
                            return `共${data.totalCount}条`
                        },
                        showSizeChanger: true,
                        showQuickJumper: true
                    } : false;
                _this && Tools.setCallback.call(_this, {pagination, list});
                resolve(data);
            }, err => {
                if (err.message) {
                    Tools.tooltip({level: 'error', content: `${err.message}，列表数据请求失败`});
                }
                reject(err);
            })
        })
    }
}